const app = getApp()

Page({
  data: {
    cellArr: [] as number[][]
  },
  onLoad: function () {
    this.startGame()
  },
  startGame() {
    this.setData({
      cellArr: [
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
      ]
    }
    )
    this.fillOneEmptyCell()
    this.fillOneEmptyCell()
  },
  fillOneEmptyCell() {
    const emptyCells = this.findEmptyCells()
    const index = this.getRandomPos(emptyCells.length)
    const [row, col] = emptyCells[index]
    this.data.cellArr[row][col] = this.getRandomValue()
    this.setData({ cellArr: this.data.cellArr })
  },
  getRandomValue(): number {
    if (Math.random() < 0.9) {
      return 2
    } else {
      return 4
    }
  },
  getRandomPos(length: number) {
    return Math.floor(Math.random() * length)
  },
  findEmptyCells(): [number, number][] {
    const result: [number, number][] = []
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (this.data.cellArr[i][j] === 0) {
          result.push([i, j])
        }
      }
    }
    return result
  }
})
